﻿using System.Diagnostics;

namespace ProjectEuler
{
    internal class Problem17
    {
        readonly int[] _lengths = new int[1001];
        
        public void Solve()
        {
            init();

            var max = 1000;

            for (int i = 13; i <= max; i++)
            {
                _lengths[i] = numLetters(i);
            }

            var sum = 0;
            for (var i = 1; i <= max; i++)
            {
                sum += _lengths[i];
            }

            Debug.WriteLine("total letters {0}", sum);
        }

        void init()
        {
            _lengths[0] = "zero".Length;
            _lengths[1] = "one".Length;
            _lengths[2] = "two".Length;
            _lengths[3] = "three".Length;
            _lengths[4] = "four".Length;
            _lengths[5] = "five".Length;
            _lengths[6] = "six".Length;
            _lengths[7] = "seven".Length;
            _lengths[8] = "eight".Length;
            _lengths[9] = "nine".Length;
            _lengths[10] = "ten".Length;
            _lengths[11] = "eleven".Length;
            _lengths[12] = "twelve".Length;
            _lengths[13] = "thirteen".Length;
            _lengths[14] = "fourteen".Length;
            _lengths[15] = "fifteen".Length;
            _lengths[16] = "sixteen".Length;
            _lengths[17] = "seventeen".Length;
            _lengths[18] = "eighteen".Length;
            _lengths[19] = "nineteen".Length;
            _lengths[20] = "twenty".Length;
            _lengths[30] = "thirty".Length;
            _lengths[40] = "forty".Length;
            _lengths[50] = "fifty".Length;
            _lengths[60] = "sixty".Length;
            _lengths[70] = "seventy".Length;
            _lengths[80] = "eighty".Length;
            _lengths[90] = "ninety".Length;


        }

        int numLetters(int number)
        {
            if (number == 1000)
                return "one thousand".Length - 1;

            if (number < 21)
                return _lengths[number];

            var result = 0;
            int n;
            if (number > 99)
            {
                n = (number / 100) % 10;
                result += _lengths[n] + "hundred".Length ;

                if (number % 100 != 0)
                    result += "and".Length;
            }

            var mod = number%100;
            if (mod > 0)
            {
                if (mod < 21)
                {
                    result += _lengths[mod];
                }
                else
                {
                    n = mod % 10;
                    if (n != 0)
                    {
                        result += _lengths[n];
                    }

                    n = (mod / 10);
                    result += _lengths[n * 10];
                }
            }
            
            return result;
        }
    }
}